package com.dynamic.mybatis.core.serialization;

import cn.hutool.core.date.DatePattern;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dynamic.mybatis.core.intercept.DynamicMappedStatementHandler;
import com.dynamic.mybatis.core.metadata.DynamicMappedStatement;
import com.dynamic.mybatis.core.metadata.DynamicMappedStatementAttributes;
import com.dynamic.mybatis.core.serialization.entity.MappedStatementEntity;
import com.dynamic.mybatis.core.serialization.mapper.MappedStatementMapper;
import com.dynamic.mybatis.core.utils.BeanUtils;
import com.dynamic.mybatis.core.utils.CollectionUtils;
import com.dynamic.mybatis.core.utils.DateUtils;
import com.dynamic.mybatis.core.utils.StringUtils;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;

import java.util.Date;
import java.util.List;

/**
 * 动态sql变更后持久化处理
 * @Description
 * @Author xs
 * @Date 2023/5/23 13:28
 */
public class MappedStatementPersistenceHandler implements DynamicMappedStatementHandler {
    private static final Log logger = LogFactory.getLog(MappedStatementPersistenceHandler.class);
    private MappedStatementMapper mappedStatementMapper;

    public MappedStatementPersistenceHandler(MappedStatementMapper mappedStatementMapper) {
        this.mappedStatementMapper = mappedStatementMapper;
    }



    @Override
    public void before(OPERATE operate, DynamicMappedStatement dms) {
        System.err.println("before mappedStatement handle.   " + operate + "   " + dms.getId());
    }

    @Override
    public void after(OPERATE operate, DynamicMappedStatement dms) {
        System.err.println("after mappedStatement handle.    " + operate + "   " + dms.getId());
        LambdaQueryWrapper<MappedStatementEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MappedStatementEntity::getTenantCode,dms.getTenantCode());
        wrapper.eq(StringUtils.isNotBlank(dms.getNamespace()),MappedStatementEntity::getNamespace,dms.getNamespace());
        wrapper.eq(MappedStatementEntity::getCode,dms.getShortId());
        wrapper.eq(MappedStatementEntity::getIsDeleted, 0);
        List<MappedStatementEntity> list = mappedStatementMapper.selectList(wrapper);

        MappedStatementEntity entity = new MappedStatementEntity();
        Integer serialNumber = 1;
        if (CollectionUtils.isNotEmpty(list)) {
            entity.setId(list.get(0).getId());
            String originalVersion = list.get(0).getVersion();
            if(StringUtils.isNotBlank(originalVersion)){
                serialNumber = Integer.valueOf(StringUtils.toString(originalVersion.substring(originalVersion.lastIndexOf(".")),"0")) + 1;
            }
        }
        entity.setVersion(DateUtils.format(new Date(), DatePattern.PURE_DATETIME_PATTERN)+"."+serialNumber);
        DynamicMappedStatementAttributes attributes = new DynamicMappedStatementAttributes();
        BeanUtils.copy(dms, attributes);
        entity.setTenantCode(dms.getTenantCode());
        entity.setNamespace(dms.getNamespace());
        entity.setCode(dms.getShortId());
        entity.setName(dms.getName());

        entity.setSqlStatement(dms.getSqlStatement());
        if(dms.getCommandType() != null){
            entity.setCommandType(dms.getCommandType().commandType());
        }
        //commandType = MERGE
        if(dms.getReturnType() != null){
            entity.setReturnType(dms.getReturnType().returnType());
        }
      //  entity.setInputParameter(JSON.toJSONString(dms.getInputParameter()));
     //   entity.setOutputParameter(JSON.toJSONString(dms.getOutputParameter()));
        entity.setTables(JSON.toJSONString(dms.getTables()));
        entity.setStatus(dms.isEnable() ? (byte) 1 : (byte) 0);
        entity.setAttribute(JSON.toJSONString(attributes));
        entity.setCreateBy(dms.getCreateBy());
        entity.setUpdateBy(dms.getUpdateBy());
        Integer result;
        if(entity.getId() != null){
            result =  mappedStatementMapper.updateById(entity);
        }else {
            result =   mappedStatementMapper.insert(entity);
        }
        logger.warn("dynamicMappedStatement save size "+JSON.toJSONString(entity).length());
        logger.warn("dynamicMappedStatement save ["+dms.getId()+"]  result ["+result+"]");
    }
}